package util

import (
	"gitee.com/sdynasty/clever/clog"
	"encoding/binary"
	"github.com/golang/protobuf/proto"
	"log"
)


const (
	HEADER        	= "SDY"
	HEADER_LENGTH 	= 3
	DATA_LENGTH       = 4
	CMD_LENGTH    	= 2
)


// 编码
func EncodePb(message proto.Message, cmd uint16, ignoreHead bool) []byte {
	data, err := proto.Marshal(message)

	if err != nil {
		log.Fatalln("EncodePb err : ", err.Error())
	}
	var m []byte
	if ignoreHead {
		m = make([]byte, 2+len(data))
		// cmd
		binary.BigEndian.PutUint16(m[0:], cmd)	//写入cmd
		// data
		copy(m[2:], data)
	} else {
		m = make([]byte, 3+4+2+len(data))
		// head
		copy(m, "SDY")
		// 长度
		binary.BigEndian.PutUint32(m[3:], uint32(len(data)) + 2)	//写入长度

		// cmd
		binary.BigEndian.PutUint16(m[7:], cmd)	//写入cmd
		// data
		copy(m[9:], data)
	}


	return m
}

// 从cmd + data截取
func GetMultiPacks(buff []byte) (fullData [][]byte, leftBuff []byte) {
	fullData = make([][]byte, 0)
	leftBuff = buff
	leftLen := len(leftBuff)
	for leftLen > HEADER_LENGTH+DATA_LENGTH {
		//如果header不是 指定的header 说明此数据已经被污染 直接返回错误
		if string(leftBuff[:HEADER_LENGTH]) != HEADER {
			clog.LogLogic().Println("header不正确:", string(leftBuff[:HEADER_LENGTH]))
			leftBuff = []byte{}
			return
		}

		// 数据字节长度不够
		msgLength := int(binary.BigEndian.Uint32(leftBuff[HEADER_LENGTH : HEADER_LENGTH+DATA_LENGTH]))
		if leftLen < HEADER_LENGTH+DATA_LENGTH+ msgLength {
			clog.LogLogic().Println("数据字节长度不够")
			return
		}

		// 完整的数据
		dataLen := HEADER_LENGTH + DATA_LENGTH +msgLength
		data := leftBuff[HEADER_LENGTH+DATA_LENGTH : dataLen]
		fullData = append(fullData, data)
		leftBuff = leftBuff[dataLen:]

		leftLen = len(leftBuff)
	}
	return
}